package day03;

public class Demo05 {
    public static void main(String[] args) {
        //排序并查找
        int[] a = {1,3,9,5,6,7,15,4,8};
        int b = 6;
        //先排序
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - i - 1; j++) {
                if(a[j] > a[j+1]){
                    int t;
                    t = a[j];
                    a[j] = a[j+1];
                    a[j+1] = t;
                }
            }
        }
        System.out.println("排序后的数组为：");
        for (int i = 0; i < a.length; i++) {//遍历排序好的数组
            System.out.print(a[i] + " ");
        }
        //二分法查找
        int min = 0;//小标
        int max = a.length - 1;//大标
        int middle = (min + max)/2;//中标
        while(true){
            if(b > a[middle]){
                min = middle + 1;
            }else if(b < a[middle]){
                max = middle - 1;
            }else{
                break;
            }
            if(min > max){
                middle = -1;
                break;
            }
            middle = (min + max)/2;//重新定义中标
        }
        System.out.println("下标为：" + middle);
    }
}
